import { useEffect, useMemo, useRef, useState } from 'react'
import { Button, Divider } from 'antd';
import {getPaperof,getsubjects,getexamlist,removeitem,Previewparper,questiontype} from '../../../services/index'
import type {paperlist,subjectslist,examlistType,PreviewdataType,queslsittype} from '../../../services/type'
import style from './paper.module.scss'
// 表格
import { Space, Table,Drawer} from 'antd';
import type { TableProps } from 'antd';
import {Link} from 'react-router-dom'
import * as XLSX from 'xlsx'
import { usePDF } from 'react-to-pdf';
import Inquire from './Inquire/Inquire';

const Paper = () => {
  // 创建人
  const [createdby,setCreatedby] = useState<paperlist[]> ([])
  // 科目汇总
  const[subjects,setSubjects] = useState<subjectslist[]> ([])
  // 考试历史
  const[examlist,setExamlist] = useState<examlistType[]> ([])
  // 预览试卷数据
  const [Previewlist,setPreviewlist] = useState<PreviewdataType | null> ( null)
  // 题目类型 (单选，多选)
  const [questionlist,setQuestionlist] =  useState<queslsittype[]> ([])
  // 试卷名称
  const [papername,setPapername] = useState ('')
  // 创建人
  const [person,setPerson] = useState ('')
  // 科目
  const [subjectstype,setSubjectsType] = useState('')
  const English = useRef(['A','B','C','D'])
  // 创建导出的文件对象
  const workbook = XLSX.utils.book_new ()
  // 导出文件的函数
  const Export = () => {
    const worksheet = XLSX.utils.json_to_sheet(examlist.map(item=>{
        return {
          '试卷名称':item.name,
          '科目类型':item.classify,
          '总分':'',
          '创建人':item.creator,
          '创建时间':new Date(item.createTime).toLocaleDateString(),
          '操作':''
        }
      }
    ))
    XLSX.utils.book_append_sheet(workbook,worksheet,'试卷汇总表.xlsx')
    XLSX.writeFile(workbook,'试卷汇总表.xlsx')
  }
  // 导出PDF
  const { toPDF, targetRef } = usePDF({filename: '试卷.pdf'});

  
  // 抽屉显示不显示
  const [open, setOpen] = useState(false);

  const getInquire = async() => {
    const res=await getexamlist({
      name:papername,
      creator:person,
      classify:subjectstype
    })
    console.log(res.data)
    setExamlist(res.data.data.list)
  }

  // 点击重置
  const purge = async() => {
    setPapername('')
    setPerson('')
    setSubjectsType('')
    const res=await getexamlist({
      name:'',
      creator:'',
      classify:''
    })
    console.log(res.data)
    setExamlist(res.data.data.list)
  }

  const showDrawer = () => {
    setOpen(true);
  };

  const onClose = () => {
    setOpen(false);
  };

  interface DataType {
    classify: string;
    name: string;
    // total: number;
    creator: string;
    createTime: string;
    _id:string
  }
  
  const columns: TableProps<DataType>['columns'] = [
    {
      title: '试卷名称',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '科目类型',
      dataIndex: 'classify',
      key: 'classify',
    },
    {
      title: '总分',
      dataIndex: 'total',
      key: 'total',
    },
    {
      title: '创建人',
      dataIndex: 'creator',
      key: 'creator',
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      key: 'createTime',
      render:(_, record)=>(
        <span>{new Date(record.createTime).toLocaleDateString(record.createTime)}</span>
      )
    },
    {
      title: '操作',
      key: 'tags',
      dataIndex: 'tags',
      render: (_, record) => (
        <>
          {
           <Space>
              <Button type="primary">编辑</Button>
              <Button style={{background:"red",color:"white"}} onClick={()=>{removeitem(record._id),getexemlist()}}>删除</Button>
              <Button onClick={()=>{showDrawer(),getPreviewlist(record._id)}}>预览试卷</Button>
           </Space>
          }
        </>
      ),
    }
  ];
  // 计算预览数组
  const data = useMemo(()=>{
    let arr = []
    const newarr = questionlist.map((item,i)=>{
      const children = Previewlist?.questions.filter(obj=>Number(obj.type) === item.value)
      return arr[i] = {
        name:item.name,
        value :item.value,
        children:children||[]
      }
    })
    return newarr
  },[Previewlist,questionlist])
  console.log(data)
  
  // 创建人
  const getcreatedby = async () => {
    const res = await getPaperof()
    console.log(res.data.data.list)
    setCreatedby(res.data.data.list)
  }
  // 科目汇总
  const getsubjectlist = async () => {
      const res = await getsubjects()
      console.log(res.data.data.list)
      setSubjects(res.data.data.list)
  }
  // 所有试卷
  const getexemlist = async () => {
    const res = await getexamlist({})
    console.log(res.data.data.list)
    setExamlist(res.data.data.list)
  }
  // 预览试卷
  const getPreviewlist = async (id:string) => {
    const res = await Previewparper(id)
    console.log(res.data)
    if(res.data.code === 200){
      console.log(res.data.data)
      setPreviewlist(res.data.data)
    }else {
      setPreviewlist(null)
    }
  }
  // 题目类型，类似于单选多选
  const getquestiontype = async () => {
    const res = await questiontype()
    console.log(res.data.data.list)
    setQuestionlist(res.data.data.list)
  }

  useEffect (()=> {
    getcreatedby()
    getsubjectlist()
    getexemlist()
    getquestiontype()
  },[])

  const changePapername = (vel:string) => {
    setPapername(vel)
  }
  const changePerson = (vel:string) => {
    setPerson(vel)
  }
  const changeSubjectsType = (vel:string) => {
    setSubjectsType(vel)
  }


  return (
    <div className={style.paper}>
      <h2>试卷库</h2>
      <div className={style.buttons}>
        <Link to='/paper/create-paper'>
          <Button type="primary" style={{marginRight:'20px'}}>创建试卷</Button>
        </Link>
        <Button type="primary" onClick={Export}>导出excel</Button>
      </div>
      <Inquire papername={papername} person={person} subjectstype={subjectstype} createdby={createdby} subjects={subjects} 
      changePapername={changePapername} changePerson={changePerson} changeSubjectsType={changeSubjectsType}
      getInquire={getInquire} purge={purge}
      />
      <div style={{marginTop:'20px'}}>
        <Table<DataType> columns={columns} dataSource={examlist} />
      </div>
      <Drawer title={
        <div className={style.header}>
          <h3>试卷预览</h3>
          <span>
            <Button style={{marginRight:'10px'}} onClick={() => toPDF()}>导出PDF</Button>
            <Button type="primary" onClick={onClose}>ok</Button>
          </span>
        </div>
      } 
      onClose={onClose} 
      open={open} 
      className={style.bottom} 
      width='700px'
      >
        <div ref={targetRef}>
          <h2>{Previewlist?.name}</h2>
          <h3 className={style.subheading}>科目：{Previewlist?.classify}</h3>
          {
            data.map(vel=>
              <div className={style.box}>
                {vel.children?<header>{vel.name}</header>:''}
                {vel.children.map((item,i)=>
                  <div className={style.item}> 
                  <div className={style.itemtop}>
                    <em>{i+1}.</em>
                    <i>{item.question}</i>
                  </div>
                  <div className={style.itembottom}>
                    {item.options.map((item,index)=>
                      <span>
                        {English.current[index]}. {item}
                      </span>
                    )}
                  </div>
                </div>
                )}
              </div>
            )
          }
        </div>
      </Drawer>
    </div>
  )
}

export default Paper